from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from rest_framework_jwt.settings import api_settings

from . import serializers
from .models import OAuthQQUser
from . utils import QQOauth
from .utils import excetption
#  url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
from rest_framework.generics import GenericAPIView
import logging
logger = logging.getLogger('django')

class QQAuthUserView(GenericAPIView):
    '''用户扫码登陆的回调处理'''

    #指定序列化器
    serializer_class = serializers.QQAuthUserSerializer
    def get(self,request):
        # 提取code请求参数
        code = request.query_params.get('code')
        if code is None:
            return Response({'message':'缺少code'}, status=status.HTTP_400_BAD_REQUEST)

        #创建OAuthQQd对象
        oauth = QQOauth()
        try:
            # 使⽤用code向QQ服务器器请求access_token
            access_token = oauth.get_access_token(code)

            # 使⽤用access_token向QQ服务器器请求openid
            openid = oauth.get_openid(access_token)
        except excetption as e:
            logger.error(e)
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)


        # 使用openid查询该QQ用户是否在美多商城中绑定过用户
        try:
            # oauth_user : 是查询出来的一条记录，就是OAuthQQUser模型对象而已
           oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果openid没绑定美多商城⽤用户，创建⽤用户并绑定到openid
            token = oauth.generate_save_user_token('open_id')
            return Response({'access_token':token})
            #return Response({'open_id': open_id})
        # 如果openid已绑定美多商城⽤用户，直接⽣生成JWT token，并返回
        else:
            # 在注册数据保存完成，响应注册数据之前，生成JWT token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            # 使用当前的注册用户user生成载荷，该载荷内部会有{"username":"", "user_id":"", "email":""}
            user = oauth_user.user # OAuthQQUser模型对象取出user
            payload = jwt_payload_handler(user)
            # JWT  token
            token = jwt_encode_handler(payload)
            return Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })

    def post(self,request):
        """绑定用户到openid
        GenericAPIView
        """
        # 获取序列化器对象
        serializer = self.get_serializer(data=request.data)
        # 开启校验
        serializer.is_valid(raise_exception=True)
        #保存校验结果并接收
        user = serializer.save()

        # 生成JWT token，并响应
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return Response({
            'token':token,
            'username':user.username,
            'user_id':user.id,
        })

class QQAuthURLView(APIView):
    '''获取QQ登陆的url'''
    def get(self,request):
        """
        提供用于qq登录的url
        """
        # next	str	否	用户QQ登录成功后进入美多商城的哪个网址
        # next表示从哪个页面进入到的登录页面，将来登录成功后，就自动回到那个页面
        next = request.query_params.get('next')
        # 获取QQ登录页面网址
        oauth = QQOauth(state=next)
        #login_url	str	是	qq登录网址
        login_url = oauth.get_qq_login_url()
        return Response({'login_url':login_url})

